const log = require('../../util/log')
const config = require('../../util/config')
const logger = require('log4js').getLogger()

async function getTaobaoAdvLink(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    if (!obj.link) {
        return new Promise((resolve, reject) => {
            reject('缺少link')
        })
    }
    if (obj.step !== 0) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao advertising link', JSON.stringify(obj))
        obj.step = 0
    }
    return new Promise((resolve, reject) => {
        this.loginTaobao().then(result => {
            step1_5.call(this, obj).then(result => {
                this.code = ''
                this.codeRequestId = 0
                this.codeText = ''
                resolve(result)
            }, result => {
                this.code = ''
                this.codeRequestId = 0
                this.codeText = ''
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

function step1_5(obj) {
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('系统错误')
        })
    }
    if (obj.step !== 1.5) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao advertising link step 1.5', obj.link)
        obj.step = 1.5
    }
    return new Promise((resolve, reject) => {
        this.getTaobaoItems({
            q: obj.link
        }).then(async result => {
            if (result.length > 0) {
                const {
                    Network,
                    Page,
                    DOM,
                    Runtime,
                    Emulation
                } = this.client;
                await Runtime.evaluate({expression: 'document.querySelectorAll(".common-product-container")[0].querySelectorAll("a")[2].click()'})
                var item = result[0]
                step1_7.call(this, obj).then(result => {
                    resolve(Object.assign(item, result))
                }, result => {
                    reject(result)
                })
            } else {
                step2.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }
        }, result => {
            reject(result)
        })
    })
}

async function step1_7(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('系统错误')
        })
    }
    if (obj.step !== 1.7) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao advertising link step 1.7', obj.link)
        obj.step = 1.7
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threebj textarea").length'})
    if (result.value == 1) {
        return step1_8.call(this, obj)
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threebj button").length'})
    if (result.value != 2) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step1_7.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threebj button")[0].click()'})
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            step1_7.call(this, obj).then(result => {
                resolve(result)
            }, result => {
                reject(result)
            })
        }, 1000)
    })
}

async function step1_8(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('系统错误')
        })
    }
    if (obj.step !== 1.8) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao advertising link step 1.8', obj.link)
        obj.step = 1.8
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".pub-threebj textarea")[0].value'})
    logger.debug('[' + __filename + ':' + __line + ']', result)
    if (result.value == '') {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step1_8.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    }
    return new Promise(resolve => {
        resolve({
            advLink: result.value.substring(result.value.lastIndexOf('http')),
            fromUsername: config.local.taobaoUsername
        })
    })
}

async function step2(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('系统错误')
        })
    }
    if (obj.step !== 2) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao advertising link step 2')
        obj.step = 2
    }
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value == 'https://pub.alimama.com/manage/links/index.htm') {
        return step3.call(this, obj)
    }
    Page.navigate({
        url: 'https://pub.alimama.com/manage/links/index.htm'
    })
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            step2.call(this, obj).then(result => {
                resolve(result)
            }, result => {
                reject(result)
            })
        }, 1000)
    })
}

async function step3(obj) {
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = this.client;
    obj.times++
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('超时')
        })
    }
    if (obj.step !== 3) {
        logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao advertising link step 3')
        obj.step = 3
    }
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value != 'https://pub.alimama.com/manage/links/index.htm') {
        return step2.call(this, obj)
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".links-panel textarea")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 0) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step3.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    }
    var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog")'})
    var cnt = result.description.substring(9, result.description.length - 1)
    if (cnt == 1) {
        return step4.call(this, obj)
    }
    await Runtime.evaluate({expression: 'document.querySelectorAll(".links-panel textarea")[0].value="' + obj.link + '"'})
    await Runtime.evaluate({expression: 'var evtObj=document.createEvent("UIEvents");evtObj.initUIEvent("keyup",true,true,window,1);document.querySelector(".links-panel textarea").dispatchEvent(evtObj);document.querySelectorAll(".links-panel button")[0].click()'})
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            step3.call(this, obj).then(result => {
                resolve(result)
            }, result => {
                reject(result)
            })
        }, 1000)
    })
}

async function step4(obj) {
    try {
        const {
            Network,
            Page,
            DOM,
            Runtime,
            Emulation
        } = this.client;
        obj.times++
        if (obj.times > config.chromeMaxTimes) {
            return new Promise((resolve, reject) => {
                logger.debug('[' + __filename + ':' + __line + '] 系统错误')
                reject('系统错误')
            })
        }
        if (obj.step !== 4) {
            logger.debug('[' + __filename + ':' + __line + ']', 'getting taobao advertising link step 4')
            obj.step = 4
        }
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt == 0) {
            return step3.call(this, obj)
        }
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".error")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt == 1) {
            return new Promise((resolve, reject) => {
                logger.debug('[' + __filename + ':' + __line + '] 该商品不能返利')
                reject('该商品不能返利')
            })
        }
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".button #clipboard-target-2")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt != 0) {
            var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".button #clipboard-target-2")[0].value'})
            return new Promise(resolve => {
                logger.debug('[' + __filename + ':' + __line + ']', result.value)
                resolve({
                    advLink: result.value,
                    fromUsername: config.local.taobaoUsername
                })
                // Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-ext-close")[0].click()'})
            })
        }

        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".button #clipboard-target-1")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt != 0) {
            var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".button #clipboard-target-1")[0].value'})
            return new Promise(resolve => {
                logger.debug('[' + __filename + ':' + __line + ']', result.value)
                resolve({
                    advLink: result.value,
                    fromUsername: config.local.taobaoUsername
                })
                // Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-ext-close")[0].click()'})
            })
        }

        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#clipboard-target")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt != 0) {
            var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#clipboard-target")[0].value'})
            return new Promise(resolve => {
                logger.debug('[' + __filename + ':' + __line + ']', result.value)
                resolve({
                    advLink: result.value,
                    fromUsername: config.local.taobaoUsername
                })
                // Runtime.evaluate({expression: 'document.querySelectorAll(".dialog-ext-close")[0].click()'})
            })
        }

        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt == 1) {//要输验证码
            var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CheckCodeImg1")'})
            var cnt = result.description.substring(9, result.description.length - 1)
            if (cnt == 1) {
                // if (!ocrMng.aipOcr) {
                //   return new Promise((resolve, reject) => {
                //     reject('没有aipOcr可用了')
                //   })
                // }
                // var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#checkcode-state")[0].className'})
                // if (result.value.indexOf('checkcode-state-right') != -1) {
                //   await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_submit")[0].click()'})
                // }
                // //换验证码
                // // await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CheckCodeImg1")[0].click()'})
                // return new Promise((resolve, reject) => {
                //   setTimeout(() => {
                //     step4(obj).then(result => {
                //       resolve(result)
                //     }, result => {
                //       reject(result)
                //     })
                //   }, 2000)
                // })
                if (this.codeText) {
                    await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_CodeInput")[0].value="' + this.codeText + '"'})
                    await Runtime.evaluate({expression: 'document.querySelectorAll("#sufei-dialog-content")[0].contentDocument.querySelectorAll("#J_submit")[0].click()'})
                    this.codeText = ''
                }
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        step4.call(this, obj).then(result => {
                            resolve(result)
                        }, result => {
                            reject(result)
                        })
                    }, 1000)
                })
            }
        }
        var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog button")'})
        var cnt = result.description.substring(9, result.description.length - 1)
        if (cnt < 4) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    step4.call(this, obj).then(result => {
                        resolve(result)
                    }, result => {
                        reject(result)
                    })
                }, 1000)
            })
        }
        await Runtime.evaluate({expression: 'document.querySelectorAll(".dialog button")[4].click()'})
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                step4.call(this, obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, 1000)
        })
    } catch (err) {
        log(err)
    }
}

module.exports = getTaobaoAdvLink
